﻿using Core.Toolkit.Core.Entitys;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Core.Toolkit.Core.Repositories.Internal
{
    public partial class BaseDBRepository<TDbContext, TEntity, TPrimaryKey>  where TEntity : Entity<TPrimaryKey> where TDbContext : DbContext
    {

        /// <summary>
        /// 删除实体
        /// </summary>
        /// <param name="entity">要删除的实体</param>
        /// <param name="autoSave">是否立即执行保存</param>
        public virtual async Task DeleteLogicAsync(TEntity entity, bool autoSave = true)
        {
            entity.IsDeleted= true;
            await this.UpdateAsync(entity,autoSave);
        }

        /// <summary>
        /// 删除实体
        /// </summary>
        /// <param name="id">实体主键</param>
        /// <param name="autoSave">是否立即执行保存</param>
        public virtual async Task DeleteLogicAsync(TPrimaryKey id, bool autoSave = true)
        {
            var entity= await this.GetAsync(id);
            await this.DeleteLogicAsync(entity, autoSave);
        }

        /// <summary>
        /// 根据条件删除实体
        /// </summary>
        /// <param name="where">lambda表达式</param>
        /// <param name="autoSave">是否自动保存</param>
        public virtual async Task DeleteLogicAsync(Expression<Func<TEntity, bool>> where, bool autoSave = true)
        {
            _dbContext.Set<TEntity>().Where(where).ToList().ForEach( async it =>  await DeleteLogicAsync(it, false));
            if (autoSave)
                await SaveAsync();
        }
    }
}
